package com.llc.mall.user.infrastructure.persist.repositoryimpl;

import com.llc.mall.user.domain.gateway.SegmentGateway;
import com.llc.mall.user.domain.user.entity.User;
import com.llc.mall.user.domain.user.repository.UserRepository;
import com.llc.mall.user.infrastructure.persist.mapper.UserMapper;
import com.llc.mall.user.infrastructure.persist.po.UserPo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
public class UserRepositoryImpl implements UserRepository {

    private final UserMapper userMapper;

    private final SegmentGateway segmentGateway;

    public UserRepositoryImpl(SegmentGateway segmentGateway, UserMapper userMapper){
        this.segmentGateway = segmentGateway;
        this.userMapper = userMapper;
    }

    @Override
    public Long save(User user) {
        if (Objects.isNull(user.getId())){
            Long userId = segmentGateway.generateId();
            UserPo userPo = new UserPo();
            userPo.setUserId(userId);
            userPo.setPic(user.getPic());
            userPo.setNickName(user.getNickName());
            userPo.setStatus(user.getStatus());
            userMapper.save(userPo);
            return userId;
        }else {
            UserPo userPo = new UserPo();
            userPo.setUserId(user.getId());
            userPo.setPic(user.getPic());
            userPo.setNickName(user.getNickName());
            userPo.setStatus(user.getStatus());
            userMapper.update(userPo);
            return user.getId();
        }
    }

    @Override
    public User findById(Long userId) {
        UserPo po = userMapper.getByUserId(userId);
        return User.builder()
                .id(po.getUserId())
                .nickName(po.getNickName())
                .pic(po.getPic())
                .status(po.getStatus())
                .build();
    }
}
